package benoli.eu.examples.getPhotos;

import java.io.InputStream;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;

public class PhotoAdapter extends SimpleCursorAdapter {
    private Cursor _cursor;
    private Context _context;
 
    public PhotoAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        _cursor = c;
        _context = context;
    }
 
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
    	Bitmap bitmap;
    	
    	super.bindView(view, context, cursor);
    	
        ImageView imageView = (ImageView) view.findViewById(R.id.image);
 
        int id = _cursor.getColumnIndex(ContactsContract.Data._ID);
        long contactId = _cursor.getLong(id);
        
        Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
        
        InputStream is = Contacts.openContactPhotoInputStream(_context.getContentResolver(), contactUri);
        
        if(is == null)
        	bitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ALPHA_8);
        else
        	bitmap = BitmapFactory.decodeStream(is);
        
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = 80;
		int newHeight = 80;
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

        imageView.setImageBitmap(resizedBitmap);
    }
}
